<?php

namespace app\model;

use app\utils\CamlHump;
use think\facade\Db;

class AppFun extends BaseModel
{
    protected $convertNameToCamel = true;
    protected $name = 'app_fun';
    static $tableTable = 'app_fun';

     // 设置字段信息
      static   $tableKeys = [
        'id'          => 'int',
        'app_id'        => 'int',
        'name'      => 'string',
        'fun_type'       => 'int',
        'fun_scope' => 'int',
        'owner_type' => 'int',
        'mobile_state' => 'int',
        'mobile_url' => 'string',
        'fun_url' => 'string',
        'parent_id' => 'int',
        'parent_id_path' => 'string',
        'deep' => 'int',
        'img' => 'string',
        'order_num' => 'int',
        'state' => 'int',
    ];

      static function createQuery($body){
          $query= parent::createQuery($body);
          if(isset($body['parentId'])){
              $query->where('parent_id', $body['parentId']);
          }
          return $query;

     }

    public static function queryWithParentId($parentId)
    {
        $query = Db::table(static::$tableTable);
        $query->where('parent_id', $parentId);
        return $query;

    }
    public  static function  findListByParentById($parentId){
        $query = Db::table(static::$tableTable);
        $query->where('parent_id', $parentId);
        $query->where('del_state', 1);
        return CamlHump::toCamlArray($query->select());
    }
    public  static function  findOneByParentById($parentId){
        $query = Db::table(static::$tableTable);
        $query->where('parent_id', $parentId);
        return CamlHump::toCamlObj($query->find());
    }
    public  static function  haveNextFromParentId($parentId){
        $query = Db::table(static::$tableTable);
        return $query->where('parent_id', $parentId)->count() > 0;
    }

    static function haveNext($id){
          if(!isset($id)){
              return false;
          }
        $query = Db::table(static::$tableTable);
        $count=$query->where('parent_id', $id)->count();
        return $count > 0;
    }

    static function fillChild($menu){
        $children=static::findListByParentById($menu['id']);
        $menu['children'] = $children;
        $menu['haveNext'] = count($children)>0;


        for ($i = 0; $i < count($children); $i++) {
            if(isset($children[$i])){
                static::fillChild($children[$i]);
            }
        }
        return $menu;

    }


}
